﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace psafth.AMB
{
    /// <summary>
    /// Used to create an object from the bytearray before you know what type of object that is received.
    /// Also used to transfer the object from the BackgroundWorker.ReportProgress method.
    /// </summary>
    public class TransferObject
    {
        /// <summary>
        /// The type of message
        /// </summary>
        public AMBMessageType MessageType
        {
            get;
            set;
        }

        /// <summary>
        /// Collection of datarows
        /// </summary>
        public List<DataRowObject> Data
        {
            get;
            private set;
        }

        /// <summary>
        /// The object as a AMBMessage
        /// </summary>
        public AMBMessage Message
        {
            get;
            private set;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="byteArray"></param>
        public TransferObject(byte[] byteArray)
        {
            List<DataRowObject> dataObjects = new List<DataRowObject>();

            // Create an known object of the byte array.
            Message = new AMBMessage(byteArray);

            // Get what type of message it is.
            this.MessageType = (AMBMessageType)Message.TypeLSB;

            // Get all data rows of the message and store them.
            foreach (byte[] arr in Message.DataRecords)
            {
                DataRowObject dataObject = new DataRowObject();

                // The data rows MSB (type of record)
                dataObject.DataType = arr[0];

                // the data rows LSB (length of record)
                dataObject.DataLength = arr[1];

                // Fetch the length of the record. 
                dataObject.Data = arr.Skip(arr.Length - dataObject.DataLength).ToArray();

                // If the records length is greater than 0, keep it.
                if (dataObject.DataLength > 0)
                    dataObjects.Add(dataObject);

            }

            // Set the data datarows
            this.Data = dataObjects;
        }
    }

    /// <summary>
    /// Helpclass that makes it easier to handle the data records of the message.
    /// </summary>
    public class DataRowObject
    {
        public DataRowObject()
        {
        }

        public int DataType
        {
            get;
            set;
        }

        public DataRowObject(int dataType, int dataLength, byte[] data)
        {
            this.DataLength = dataLength;
            this.DataType = dataType;
            this.Data = data;
        }

        public int DataLength { get; set; }

        public byte[] Data { get; set; }

    }
}
